package com.szzg10.webservice.chapter3;

import java.io.IOException;
import java.util.Set;
import java.util.UUID;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

public class UUIDHandler implements SOAPHandler<SOAPMessageContext> {

	@Override
	public boolean handleMessage(SOAPMessageContext context) {
		
		Boolean flag_request = (Boolean)context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
		
		if(flag_request) {
			try {
				SOAPMessage message = context.getMessage();
				SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
				SOAPHeader header = envelope.getHeader();
				
				if(header == null) {
					header = envelope.addHeader();
				}
				
				QName qName = new QName("http://com.szzg10.webservice.chapter3", "uuid");
				SOAPHeaderElement headerElement = header.addHeaderElement(qName);
				headerElement.setActor(SOAPConstants.URI_SOAP_ACTOR_NEXT);
				headerElement.addTextNode(UUID.randomUUID().toString());
				
				message.saveChanges();
				
				message.writeTo(System.out);
			} catch(SOAPException e) {
				System.err.println(e);
			} catch(IOException e) {
				System.err.println(e);
			}
		}
		
		return true;
	}
	
	@Override
	public boolean handleFault(SOAPMessageContext context) {
		
		try {
			context.getMessage().writeTo(System.out);
		} catch (SOAPException e) {
			System.err.println(e);
		} catch (IOException e) {
			System.err.println(e);
		}
		
		return true;
	}
	
	@Override
	public void close(MessageContext arg0) {}

	@Override
	public Set<QName> getHeaders() {
		return null;
	}

}
